﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletMotionController : MonoBehaviour
{
    public List<BulletMotion> initMotions;
    public bool isSpinSprite;
    [HideInInspector]
    public Vector2 towards;
    [HideInInspector]
    public Vector2 targetMovement = Vector2.zero;

    private List<BulletMotion> motions = new List<BulletMotion>();
    private Rigidbody2D body;
    private float time;

    private void Awake()
    {
        foreach (BulletMotion motion in initMotions)
        {
            AddMotion(motion);
        }
        body = GetComponent<Rigidbody2D>();
        time = 0;
    }

    private void Move()
    {
        targetMovement = Vector2.zero;
        for (int i = 0; i < motions.Count; i++)
        {
            motions[i].Awaking(time);
            targetMovement += motions[i].Motion(time);
            motions[i].Ending(time);
        }

        transform.position += (Vector3)targetMovement;
    }

    private void Update()
    {
        time += Time.deltaTime;
        if (isSpinSprite)
        {
            transform.localEulerAngles = new Vector3(0, 0, Vector2.SignedAngle(Vector2.left, towards));
        }
    }

    private void FixedUpdate()
    {
        Move();
    }

    public void AddMotion(BulletMotion m)
    {
        BulletMotion motion = Instantiate(m);
        motions.Add(motion); 
        motion.motionController = this;
    }

    public void AddMotion(List<BulletMotion> bulletMotions)
    {
        foreach (BulletMotion bulletMotion in bulletMotions)
        {
            AddMotion(bulletMotion);
        }
    }

    public void AddMotion(string path)
    {
        if (Resources.Load(path) != null)
        {
            BulletMotion motion = Instantiate((BulletMotion)Resources.Load(path));
            if (Resources.Load(path) is BulletMotion)
            {
                motions.Add(motion);
                motion.motionController = this;
            }
            else
            {
                Debug.LogError("加载错误。该资源不是预期类型。");
            }
        }
        else
        {
            Debug.LogError("加载错误。可能是路径不对。");
        }
    }

    public void RemoveMotion(BulletMotion motion)
    {
        motions.Remove(motion);
    }
}